package com.xyht.medicine_management_system.modules.medicine.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.common.util.TimeUtil;
import com.xyht.medicine_management_system.modules.medicine.entity.MmsMedicine;
import com.xyht.medicine_management_system.modules.medicine.entity.MmsMedicineFootprint;
import com.xyht.medicine_management_system.modules.medicine.entity.resp.MmsMedicineDetailResp;
import com.xyht.medicine_management_system.modules.medicine.entity.resp.MmsMedicineFootprintResp;
import com.xyht.medicine_management_system.modules.medicine.mapper.MmsMedicineFootprintMapper;
import com.xyht.medicine_management_system.modules.medicine.mapper.MmsMedicineMapper;
import com.xyht.medicine_management_system.modules.medicine.service.MmsMedicineFootprintService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.medicine_management_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.medicine_management_system.modules.medicine.constant.PageConstant.PAGE_NUM;
import static com.xyht.medicine_management_system.modules.medicine.constant.PageConstant.PAGE_SIZE;

/**
 * <p>
 * 药品足迹 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-12-05
 */
@Service
public class MmsMedicineFootprintServiceImpl extends ServiceImpl<MmsMedicineFootprintMapper, MmsMedicineFootprint> implements MmsMedicineFootprintService {

    @Resource
    private MmsMedicineFootprintMapper footprintMapper;
    @Resource
    private MmsMedicineMapper medicineMapper;

    @Override
    public ResponseResult getMyFootprintList(Integer pageNum, Integer pageSize, String footprintDateStr, String userId) {
        Page<MmsMedicineFootprint> page = new Page<>(pageNum,pageSize);
        QueryWrapper<MmsMedicineFootprint> footprintQueryWrapper = new QueryWrapper<>();
        footprintQueryWrapper
                .select("footprint_date")
                .lambda()
                .eq(MmsMedicineFootprint::getUserId,userId)
                .groupBy(MmsMedicineFootprint::getFootprintDate)
                .orderByDesc(MmsMedicineFootprint::getFootprintDate);

        if (!isNullOrEmpty(footprintDateStr)) {
            Date footprintDate = TimeUtil.StringtoDate(footprintDateStr);
            if (footprintDate != null) {
                footprintQueryWrapper
                        .lambda()
                        .ge(MmsMedicineFootprint::getCreateTime, TimeUtil.GetStartDate(footprintDate))
                        .le(MmsMedicineFootprint::getCreateTime, TimeUtil.GetEndDate(footprintDate));
            }
        } else {
            //30天内的足迹
            footprintQueryWrapper
                    .lambda()
                    .ge(MmsMedicineFootprint::getCreateTime, TimeUtil.GetStartDate(TimeUtil.AddDays(new Date(),-29)))
                    .le(MmsMedicineFootprint::getCreateTime, TimeUtil.GetEndDate(new Date()));
        }

        footprintMapper.selectPage(page, footprintQueryWrapper);
        List<MmsMedicineFootprintResp> footprintList = page.getRecords()
                .stream()
                .map(mmsFootprintDate -> {
                    MmsMedicineFootprintResp medicineFootprintResp = new MmsMedicineFootprintResp();

                    //过滤后查自己的足迹
                    LambdaQueryWrapper<MmsMedicineFootprint> medicineFootprintLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    medicineFootprintLambdaQueryWrapper
                            .eq(MmsMedicineFootprint::getUserId, userId)
                            .eq(MmsMedicineFootprint::getFootprintDate, mmsFootprintDate.getFootprintDate());

                    //一天内 最多展示6个商品
                    Page<MmsMedicineFootprint> medicineFootprintPage = new Page<>(PAGE_NUM, PAGE_SIZE);
                    footprintMapper.selectPage(medicineFootprintPage, medicineFootprintLambdaQueryWrapper);
                    //一天内的总足迹量
                    Integer sum = footprintMapper.selectCount(medicineFootprintLambdaQueryWrapper);
                    int remainingQuantity = sum - PAGE_SIZE;
                    //商品信息
                    List<MmsMedicineDetailResp> medicineDetailList = medicineFootprintPage.getRecords()
                            .stream()
                            .collect(Collectors.toMap(footprint  ->{
                                String medicineInfo = footprint.getMedicineInfo();
                                MmsMedicineDetailResp medicineDetailResp = new MmsMedicineDetailResp();
                                MmsMedicine medicine = JSONObject.parseObject(medicineInfo, MmsMedicine.class);
                                return medicine.getId();
                            }, p -> p, (p1, p2) -> p1))
                            .values()
                            .stream()
                            .map(mmsMedicineFootprint -> {
                                MmsMedicineDetailResp medicineDetailResp = new MmsMedicineDetailResp();
                                MmsMedicine medicine = JSONObject.parseObject(mmsMedicineFootprint.getMedicineInfo(), MmsMedicine.class);
                                BeanUtils.copyProperties(medicine, medicineDetailResp);
                                return medicineDetailResp;
                            })
                            .collect(Collectors.toList());

                    medicineFootprintResp.setFootDate(TimeUtil.DateFormatSting(mmsFootprintDate.getFootprintDate()));
                    medicineFootprintResp.setRemainingQuantity(remainingQuantity);

                    medicineFootprintResp.setMedicineInfoList(medicineDetailList);
                    return medicineFootprintResp;
                })
                .collect(Collectors.toList());

        int total = (int) page.getTotal();
        return CommonResult.success(footprintList,total);
    }

    @Override
    public ResponseResult getOtherMyFootprintList(String userId, String footprintDate) {

        if (isNullOrEmpty(footprintDate)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        List<MmsMedicineDetailResp> medicineDetailList = footprintMapper.selectList(new LambdaQueryWrapper<MmsMedicineFootprint>()
                .eq(MmsMedicineFootprint::getFootprintDate, footprintDate)
                .eq(MmsMedicineFootprint::getUserId, userId))
                .stream()
                .map(medicineFootprint -> {
                    MmsMedicineDetailResp medicineDetailResp = new MmsMedicineDetailResp();
                    MmsMedicine medicine = JSONObject.parseObject(medicineFootprint.getMedicineInfo(), MmsMedicine.class);
                    BeanUtils.copyProperties(medicine, medicineDetailResp);
                    return medicineDetailResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(medicineDetailList);
    }
}
